﻿using Microsoft.SharePoint;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Portal
{
    class PortalSocialLogic
    {
        private static string domain = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;
        

        public static bool AddComment(string itemId, string user, string commentbody)
        {
            SPWeb web = SPContext.Current.Web;

            web.AllowUnsafeUpdates = true;
            SPList list = web.GetList("/Lists/Comments/");
            SPListItem item = list.AddItem();
            SPUser spu = SPContext.Current.Web.CurrentUser;

            string userAccount = PortalSocialLogic.domain + "\\" + user;

            item["CommentID"] = itemId;
            item["CommentBody"] = commentbody;
            item["Commenter"] = web.EnsureUser(userAccount);
            item.Update();

            web.AllowUnsafeUpdates = false;
            return true;
        }

        public static string  AddDeleteLike(string userLogin, string itemId, string isCurrentUserLike)
        {
            string iditem = itemId;
            try
            {
                SPWeb web = SPContext.Current.Web;

                web.AllowUnsafeUpdates = true;
                SPList list = web.GetList("/Lists/Likes/");
                if (isCurrentUserLike == "Like")
                {
                    SPListItem item = list.AddItem();
                    string userAccount = PortalSocialLogic.domain + "\\" + userLogin;
                    item["LikeID"] = itemId;
                    item["Liker"] = web.EnsureUser(userAccount);
                    item.Update();
                }
                else
                {
                    SPQuery query = new SPQuery();
                    query.Query = @"<Where>
                                      <And>
                                         <Eq>
                                            <FieldRef Name='LikeID' />
                                            <Value Type='Lookup'>"+itemId+@"</Value>
                                         </Eq>
                                         <Eq>
                                            <FieldRef Name='Liker' />
                                            <Value Type='User'>"+SPContext.Current.Web.CurrentUser.Name+@"</Value>
                                         </Eq>
                                      </And>
                                   </Where>";
                    query.RowLimit = 1;
                    SPListItemCollection splic = list.GetItems(query);
                    splic[0].Delete();
                   
                }



                web.AllowUnsafeUpdates = false;
            }
            catch (Exception ex)
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {


                    string cs = "Portal";
                    EventLog elog = new EventLog();

                    if (!EventLog.SourceExists(cs))
                    {
                        EventLog.CreateEventSource(cs, cs);
                    }
                    elog.Source = cs;
                    elog.EnableRaisingEvents = true;
                    elog.WriteEntry(ex.ToString(), EventLogEntryType.Error);
                    elog.Close();

                });
            }
            
            return iditem ;

        }

        public static LikesDetail GetAllLikes(string id)
         {
            
             var like = new LikesDetail
             {
                
                 IsCurrentUserLike = false,
                
                 NumberOfLikes = 0,
                 UserLikes = new List<string>()
             };
             SPWeb web = SPContext.Current.Web;
             SPList list = web.GetList("/Lists/Likes/");
             SPQuery query = new SPQuery();
             query.Query = @"<Where>
                                <Eq>
                                    <FieldRef Name='LikeID' />
                                    <Value Type='Lookup'>"+id+@"</Value>
                                </Eq>
                            </Where>";
             query.ViewFields = @"<FieldRef Name='ID'/>
                                  <FieldRef Name='Liker'/>
                                  <FieldRef Name='LikeID'/>                                                                   
                                ";

             SPListItemCollection splic = list.GetItems(query);

             
             foreach(SPListItem item in splic)
             {

                 like.UserLikes.Add(item["Liker"].ToString().Split('#')[1]);
                 
             }

             like.NumberOfLikes = splic.Count;
             like.IsCurrentUserLike=iscurrentLike(id);
             like.iditem = id;
            return like;

         }



         public static List<CommentDetails> AllComments(string id)
         {
             var listString = new List<CommentDetails>();
             
             SPWeb web = SPContext.Current.Web;
             SPList list = web.GetList("/Lists/Comments/");
             SPQuery query = new SPQuery();
             query.Query = @"<Where>
                                <Eq>
                                    <FieldRef Name='CommentID' />
                                    <Value Type='Lookup'>" + id + @"</Value>
                                </Eq>
                            </Where> 
                            <OrderBy>
                                <FieldRef Name='Created' Ascending='False' />
                            </OrderBy>";
             query.ViewFields = @"<FieldRef Name='ID'/>
                                <FieldRef Name='Commenter'/>
                                <FieldRef Name='CommentBody'/>
                                <FieldRef Name='Created'/>   
                                <FieldRef Name='CommentID'/>                                                                    
                                ";

             SPListItemCollection splic = list.GetItems(query);
             foreach (SPListItem item in splic)
             {
                 //CommentDetails comment = new CommentDetails();
                 //comment.CommentBody = item["CommentBody"].ToString();
                 //comment.Commentor = item["Commenter"].ToString();
                 //comment.CommentDate = item["Created"].ToString();

                 listString.Add(new CommentDetails
                 {
                     CommentBody = item["CommentBody"].ToString(),

                     Commentor = item["Commenter"].ToString().Split('#')[1],
                     CommentDate = item["Created"].ToString(),
                     itemID=item["CommentID"].ToString(),
                 });

                 
                 //listString.Add(item["CommentBody"].ToString());
             }
             return listString;
         }

        public static bool iscurrentLike(string id)
        {
            bool isLike = false;
            if (SPContext.Current.Web.CurrentUser != null)
            {
               
                var listString = new LikesDetail();
                SPWeb web = SPContext.Current.Web;
                SPList list = web.GetList("/Lists/Likes/");
                SPQuery query = new SPQuery();
                query.Query = @" <Where>
                              <And>
                                 <Eq>
                                    <FieldRef Name='LikeID' />
                                    <Value Type='Lookup'>" + id + @"</Value>
                                 </Eq>
                                 <Eq>
                                    <FieldRef Name='Liker' />
                                    <Value Type='User'>" + SPContext.Current.Web.CurrentUser.Name + @"</Value>
                                 </Eq>
                              </And>
                           </Where>";
                query.ViewFields = @"<FieldRef Name='ID'/>                                                                                                   
                                ";

                SPListItemCollection splic = list.GetItems(query);
                if (splic.Count > 0)
                    isLike = true;
                else
                    isLike = false;
            }

            return isLike;
        }

    }

   public  class CommentDetails    {
        
        public string CommentBody { get; set; }        
        public string Commentor { get; set; }   
        public string CommentDate { get; set; }
        public string itemID { get; set; }
       
    }

   public class LikesDetail
   {

       public int NumberOfLikes { get; set; }
       public List<string> UserLikes { get; set; }
       public bool IsCurrentUserLike { get; set; }
       public string iditem { get; set; }
       
   }
}

